import { _decorator, Component, director, instantiate, Node, Prefab } from 'cc';
import { NetWorkManager } from '../Global/NetWorkManager';
import { ApiMsgEnum, IMsgRoom } from '../Common';
import DataManager from '../Global/DataManager';
import { SceneEnum } from '../Enum';
import { PlayerManager } from '../UI/PlayerManager';
import { deepClone } from '../Utils';
const { ccclass, property } = _decorator;
/**
 * 房间内管理
 */
@ccclass('RoomManager')
export class RoomManager extends Component {
    @property(Node)
    playerContainer:Node

    @property(Prefab)
    playerPrefab:Prefab

    onLoad() {
        //房间内消息同步
        NetWorkManager.Instance.listenMsg(ApiMsgEnum.MsgRoom,this.renderPlayer,this)
        //开始游戏
        NetWorkManager.Instance.listenMsg(ApiMsgEnum.MsgGameStart,this.handleGameStart,this)
    }
    start(){ 
        this.renderPlayer({
            room:DataManager.Instance.roomInfo
        })     
    }   
    onDestroy() {
        //解绑
        NetWorkManager.Instance.unlistenMsg(ApiMsgEnum.MsgRoom,this.renderPlayer,this)
        NetWorkManager.Instance.unlistenMsg(ApiMsgEnum.MsgGameStart,this.handleGameStart,this)
    }
    
    /**
     *  渲染玩家列表
     */
    renderPlayer({room:{players:list}}:IMsgRoom){
        for (const c of this.playerContainer.children) {
            c.active=false
        }

        while (this.playerContainer.children.length<list.length){
            const node = instantiate(this.playerPrefab)
            node.active=false
            node.setParent(this.playerContainer)
        }
        
        for (let i = 0; i < list.length; i++) {
            const data = list[i];
            const node = this.playerContainer.children[i]
            node.getComponent(PlayerManager).init(data)
        }
    }

    /**
     * 离开房间
     */
    async handleLeaveRoom(){
        //调用callApi方法
        const {success,error,res} = await NetWorkManager.Instance.callApi(ApiMsgEnum.ApiRoomLeave,{});
        if(!success){
            console.error(error)
            return
        }
        //清空roomInfo
        DataManager.Instance.roomInfo=null     
        director.loadScene(SceneEnum.Hall)
        
    }
    
    /**
     * 点击开始游戏按钮
     */
    async handleStart(){
        //调用callApi方法
        const {success,error,res} = await NetWorkManager.Instance.callApi(ApiMsgEnum.ApiGameStart,{});
        if(!success){
            console.error(error)
            return
        }
    }
    
    /**
     * 游戏开始
     */
    handleGameStart({state}){
        DataManager.Instance.state = state
        //保存上一次的服务端状态，用来做预测回滚
        DataManager.Instance.lastState = deepClone(DataManager.Instance.state)
        director.loadScene(SceneEnum.Battle)
    }
}

